package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    long lastTime = 0;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/json; charset=utf8");
        // 让前端检测当前的登录状态
        HttpSession session = req.getSession(false);
        User user = (User) session.getAttribute("user");
        String count = req.getParameter("count");
        String photo = req.getParameter("photo");
        if (count != null){
            // 获取该对象列表信息
            List<Blog> blogs = getBlogsByUser(user);
            resp.getWriter().write(objectMapper.writeValueAsString(blogs));
        }else if (photo != null){
            UserDao userDao = new UserDao();
            String photoAndGit = userDao.findPhotoByName(user.getUserName());
            String photoName = photoAndGit.split(" ")[0];
            String github = photoAndGit.split(" ")[1];
            user.setPhoto(photoName);
            if (github == null || github.equals("null")){
                github = "";
            }
            user.setGithub(github);
            user.setPassword("");
            resp.getWriter().write(objectMapper.writeValueAsString(user));
        }else{
            // 获取左侧对象信息
            resp.getWriter().write(objectMapper.writeValueAsString(user));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        UserDao userDao = new UserDao();

        String delete = req.getParameter("delete");
        // 是要注销用户
        if (delete != null && delete.equals("yes")){
            HttpSession session = req.getSession(false);
            User user = (User) session.getAttribute("user");
            User.deletePhoto(user.getUserName());
            userDao.deleteUser(user);// 删除用户信息
            userDao.deleteUserBlogs(user);// 删除用户博客信息
            return;
        }

        String change = req.getParameter("change");
        // 是要更换头像
        if (change != null && change.equals("yes")){
            long nowTime = System.currentTimeMillis();
            if (nowTime - lastTime <= 1000){
                resp.getWriter().write("wait");
                return;
            }
            lastTime = nowTime;
            HttpSession session = req.getSession(false);
            User user = (User) session.getAttribute("user");
            String photoAndGithub = userDao.findPhotoByName(user.getUserName());
            String photo = photoAndGithub.split(" ")[0];
            // 得到新的照片名
            String photos[] = photo.split("_");
            int number = Integer.parseInt(photos[1]);
            number++;
            photo = photos[0] + "_" + number;
            user.setPhoto(photo);
            // 更新数据库的信息
            userDao.updateUser(user);
            // 根据用户名生成用户头像

            String path = req.getRealPath(req.getServletPath());
            path = path.substring(0, path.lastIndexOf("\\"));
            path += "\\image\\" + user.getUserName() + "_" + number +".png";

            DrawPicture.generateImg(user.getPhoto(), path);
            return;
        }

        // 是要注册用户
        // 核查用户是否存在
        User userEnroll = objectMapper.readValue(req.getInputStream(), User.class);
        String username = userEnroll.getUserName();
        String password = userEnroll.getPassword();
        String github = userEnroll.getGithub();

        if (github == null || "".equals(github)){
            github = "NULL";
        }
        if (username == null || "".equals(username) || password == null || "".equals(password)){
            // 注册失败
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("null");
            return;
        }

        // 和数据库的进行比较
        User user = userDao.selectUser(username);// 拿到 user用户
        if (user != null){
            // 注册失败
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("exist");
            return;
        }

        // 生成默认头像
        userEnroll.setPhoto(username + "_1");
        userEnroll.setGithub(github);

        String path = req.getRealPath(req.getServletPath());
        path = path.substring(0, path.lastIndexOf("\\"));
        path += "\\image\\" + userEnroll.getUserName() + "_1.png";
        DrawPicture.generateImg(userEnroll.getPhoto(), path);
        // 添加用户到数据库
        userDao.addUser(userEnroll);
        resp.getWriter().write("success");
    }

    public List<Blog> getBlogsByUser(User user){
        BlogDao blogDao = new BlogDao();
        return blogDao.selectBlogsByUser(user.getUserId());
    }
}
